/*
 * Copyright (C) 2011 The Code Bakers
 * Authors: Cleuton Sampaio e Francisco Rodrigues
 * e-mail: thecodebakers@gmail.com
 * Project: 
 * Site: http://www.thecodebakers.org
 *
 * Licensed under the GNU GPL, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://gplv3.fsf.org/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * @author Cleuton Sampaio e Francisco Rogrigues - thecodebakers@gmail.com
 */
package org.thecodebakers.phonegap.plugins.androidstring;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.res.Resources;
import android.util.Log;

import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import com.phonegap.api.PluginResult.Status;

public class PGAndroidString extends Plugin {
	
	private static final String TAG = "PGAndroidString";

	@Override
	public PluginResult execute(String action, JSONArray dados, String arg2) {
		Log.d(TAG, "Entrou no execute");

		PluginResult result = null;
		JSONObject resString = new JSONObject();
		if (action.equalsIgnoreCase("getResourceString")) {
			try {
					Context ctx = PGAndroidStringSingleton.context;
					Resources res = ctx.getResources();
					String packageName = ctx.getPackageName();
					JSONObject pesquisa = dados.getJSONObject(0);
					int resourceID = res.getIdentifier(pesquisa.getString("nome"), "string", packageName);
					String texto = res.getString(resourceID);
					Log.d(TAG, "Retornando: " + texto);
					resString.put("value", texto);
					result = new PluginResult(Status.OK, resString);
				} catch (JSONException jsonEx) {
					Log.d(TAG, "JSON Exception "+ jsonEx.getMessage());
					result = new PluginResult(Status.JSON_EXCEPTION);
				}
				catch (Resources.NotFoundException rex) {
					Log.e(TAG, "Não achou o recurso");
					try {
						resString.put("value", "Não achou o recurso");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					result = new PluginResult(Status.JSON_EXCEPTION, resString);
				}
		}
		else {
			result = new PluginResult(Status.INVALID_ACTION);
			Log.d(TAG, "acao invalida : "+action);
		}
		return result;
	}
}
